package com.jgc.future;


import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2022/3/22.
 */
public class CompletableFutureMallTest {
    static List<NetMall> list = Arrays.asList(
            new NetMall("jd"),
            new NetMall("tabao"),
            new NetMall("pdd")
    );
    public static List<String> getPriceByStep(List<NetMall> list,String produceName){
        return list.stream().map(netMall -> String.format("商品名%s,价格%.2f",netMall.getMallName(),netMall.calcPrices(produceName))).collect(Collectors.toList());
    }

    /**
     * List<NetMall> ->  List<CompletableFuture<String>> -->List<String>
     * @param list
     * @param produceName
     * @return
     */
    public static List<String> getPriceByAsnc(List<NetMall> list,String produceName){
        return list.stream().map(netMall -> CompletableFuture.supplyAsync(() -> String.format("商品名%s,价格%.2f", netMall.getMallName(), netMall.calcPrices(produceName))))
                .collect(Collectors.toList()).stream().map(CompletableFuture::join).collect(Collectors.toList());
    }
    public static void main(String[] args) {
//        getPriceByStep();
        long l = System.currentTimeMillis();
        List<String> list1 = getPriceByStep(list, "mysql");
        for (String element:list1){
            System.out.println(element);
        }
        long l1 = System.currentTimeMillis();
        System.out.println("----consttime" + (l1 - l) + "毫秒");
        List<String> list2 = getPriceByAsnc(list, "mysql");
        for (String element: list2){
            System.out.println(element);
        }
        long l2 = System.currentTimeMillis();
        System.out.println("----consttime" + (l2 - l1) + "毫秒");



    }
}
class NetMall{

    private String mallName;

    public String getMallName() {
        return mallName;
    }

    public void setMallName(String mallName) {
        this.mallName = mallName;
    }

    public NetMall(String mallName) {
        this.mallName = mallName;
    }
    public double calcPrices(String productName){
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
    }
}

